package com.ai.smlcore.util;

import com.ai.smlcore.service.ICacheService;
import com.ai.smlcore.service.impl.CacheServiceImpl;

/**
 * 更新充值结果线程安全辅助类
 * 
 * @author ShenHuaJie
 */
public final class RechargeResultUtil {
	private RechargeResultUtil() {
	}

	private static final ICacheService cacheService = new CacheServiceImpl();
	private static final String KEYPREFIX = "FLOW-RCHRG-RESULT-";

	/** 保存订单号(线程安全) */
	public static boolean add(String orderId) {
		String cacheKey = KEYPREFIX + orderId;
		if (!cacheService.exists(cacheKey)) {
			synchronized (cacheService) {
				if (!cacheService.exists(cacheKey)) {
					if (cacheService.setnx(cacheKey, String.valueOf(System.currentTimeMillis()))) {
						return true;
					}
				}
			}
		}
		int expires = 1000 * 60 * 5;
		String currentValue = cacheService.getFromCache(cacheKey);
		if (currentValue != null && Long.parseLong(currentValue) < System.currentTimeMillis() - expires) {
			cacheService.put2Cache(cacheKey, String.valueOf(System.currentTimeMillis()), expires);
			return true;
		}
		return false;
	}

	/** 移除订单号 */
	public static void remove(String orderId) {
		String cacheKey = KEYPREFIX + orderId;
		cacheService.delFromCache(cacheKey);
	}
}
